package com.ghsc.ghxc.jsb.ui.my.activity

import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityEditAddressBinding
import com.ghsc.ghxc.jsb.ext.intentExtras
import com.ghsc.ghxc.jsb.ext.setOnFastClickListener
import com.ghsc.ghxc.jsb.ext.textString
import com.ghsc.ghxc.jsb.ui.bean.AddressBeanData
import com.ghsc.ghxc.jsb.ui.my.bean.AddressDetailBean
import com.ghsc.ghxc.jsb.ui.my.bean.AddressJsonBean
import com.ghsc.ghxc.jsb.utils.JsonUtils.getJson
import com.google.gson.Gson
import org.json.JSONArray

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.my.activity
 * 类名：EditAddressActivity
 * 创建时间：2024/4/25 16:09
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class EditAddressActivity : BaseVMActivity<AddressViewModel, ActivityEditAddressBinding>(){
    override fun attachLayoutRes(): Int {
        return R.layout.activity_edit_address
    }

    override fun attachVMClass(): Class<AddressViewModel>? {
        return AddressViewModel::class.java
    }




    var bundle:Bundle?=null
    var addressBean :AddressDetailBean ?=null
    var id:Int=-1

    private var options1Items: List<AddressJsonBean> = ArrayList()
    private val options2Items = ArrayList<ArrayList<String>>()
    private val options3Items = ArrayList<ArrayList<ArrayList<String>>>()
    private var province = ""
    private var city = ""
    private var area = ""
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        bundle=intent.extras
        if (bundle!=null){
            addressBean= bundle!!.getSerializable("addressBean") as AddressDetailBean?
        }
        addressBean?.let {
            id=it.id
            binding.etName.setText(it.name)
            binding.etPhone.setText(it.mobile)
            province=it.province
            city=it.city
            area=it.area
            binding.tvSelectAddress.text = "$province $city $area"
            binding.etAddress.setText(it.site)
            binding.ivDefault.isSelected = it.ifdefault == 1
        }
        binding.apply {
            bar.topTitle.text = "编辑收货地址"
            bar.topLeftView.setOnClickListener { finish() }
            bar.topRightView.visibility = View.GONE
        }
        binding.tvSelectAddress.setOnFastClickListener {
            initAddData()
        }
        binding.ivDefault.setOnFastClickListener {
            binding.ivDefault.isSelected = !binding.ivDefault.isSelected
        }
        binding.apply {
            stSaveAddress.setOnFastClickListener {
                val name = etName.textString
                val phone = etPhone.textString
                val selectAddress = tvSelectAddress.textString
                val address = etAddress.textString
                val isDefaultSelect = ivDefault.isSelected
                if (name.isEmpty()){
                    showToast("请输入收货人姓名")
                    return@setOnFastClickListener
                }
                if (phone.isEmpty()){
                    showToast("请输入收货人手机号码")
                    return@setOnFastClickListener
                }
                if (phone.length != 11){
                    showToast("请输入正确的收货人手机号码")
                    return@setOnFastClickListener
                }
                if (selectAddress.isEmpty()){
                    showToast("请选择地址")
                    return@setOnFastClickListener
                }
                if (address.isEmpty()){
                    showToast("请输入详细地址")
                    return@setOnFastClickListener
                }
                val map = HashMap<String,Any>()
                map["name"] = name
                map["mobile"] = phone
                map["province"] = province
                map["city"] = city
                map["area"] = area
                map["site"] = address
                map["ifdefault"] = if (isDefaultSelect) 1 else 0
                if (id >-1) {
                    //编辑地址
                    map["id"] = id
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShouHuositeUpdMethod(it1) }
                } else {
                    //新建地址
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShouhuoSiteAddMethod(it1) }
                }
            }
        }
    }
    override fun initData() {
        super.initData()
    }
    override fun initRequestObserver() {
        super.initRequestObserver()
        binding.apply {
            mViewModel.apply {
                errorMsg.observe(this@EditAddressActivity) {
                    showToast(it)
                }
                againLoginMsg.observe(this@EditAddressActivity) {
                    showToast(CustKey.IN_AGAIN_MSG)
                    LoginHelper.startLoginPage()
                }
//                //更新地址
                onShouHuositeUpdData.observe(this@EditAddressActivity){
                    showToast("地址修改成功")
                    RxBus.getDefault().post(RxBusBean(CustKey.REFRESH_ADDRESS, CustKey.REFRESH_ADDRESS))
                    finish()
                }
//                //添加地址
                onShouhuoSiteAddData.observe(this@EditAddressActivity){
                    showToast("地址添加成功")
                    RxBus.getDefault().post(RxBusBean(CustKey.REFRESH_ADDRESS, CustKey.REFRESH_ADDRESS))
                    finish()
                }
            }
        }
    }
    private fun initAddData(){
        if(options1Items.isNotEmpty()){
            showPickerView()
        }else{
            val jsonData: String = getJson(this, "areaData.json")
            val addressBean = GsonUtil.gsonToJsonClass(jsonData, AddressBeanData::class.java)
            options1Items = addressBean
            for (i in addressBean.indices) { //遍历省份
                val cityList = ArrayList<String>() //该省的城市列表（第二级）
                val province_AreaList = ArrayList<ArrayList<String>>() //该省的所有地区列表（第三极）
                for ( c in addressBean[i].children.indices) { //遍历该省份的所有城市
                    val cityName = addressBean[i].children[c].name
                    cityList.add(cityName) //添加城市
                    val city_AreaList = ArrayList<String>() //该城市的所有地区列表
                    for (a in addressBean[i].children[c].children.indices) {
                        city_AreaList.add(addressBean[i].children[c].children[a].name)
                    }
                    province_AreaList.add(city_AreaList) //添加该省所有地区数据
                }
                /**
                 * 添加城市数据
                 */
                options2Items.add(cityList)
                /**
                 * 添加地区数据
                 */
                options3Items.add(province_AreaList)
            }
            showPickerView()
        }



    }

    /**
     * 弹出选择器
     */
    private fun showPickerView() {
        var provinceIndex = 0
        var cityIndex = 0
        var areaIndex = 0
        options1Items.forEachIndexed { index1, options1Item ->
            if (options1Item.name == province) {
                provinceIndex = index1
                options2Items[index1].forEachIndexed { index2, option2Item ->
                    if (option2Item == city) {
                        cityIndex = index2
                        options3Items[index1][index2].forEachIndexed { index3, options3Item ->
                            if (options3Item == area) {
                                areaIndex = index3
                            }
                        }
                    }
                }
            }
        }
        val pvOptions: OptionsPickerView<Any> = OptionsPickerBuilder(
            this
        ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
            val opt1tx =
                if (options1Items.isNotEmpty()) options1Items[options1].pickerViewText else ""
            val opt2tx =
                if (options2Items.size > 0 && options2Items[options1].size > 0) options2Items[options1][options2] else ""
            val opt3tx =
                if (options2Items.size > 0 && options3Items[options1].size > 0 && options3Items[options1][options2].size > 0) options3Items[options1][options2][options3] else ""
            province = opt1tx
            city = opt2tx
            area = opt3tx
            binding.tvSelectAddress.text =
                opt1tx + "${if (opt1tx == opt2tx) "" else " $opt2tx"}" + " $opt3tx"
        }
            .setTitleText("地址选择")
            .setDividerColor(Color.BLACK)
            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
            .setSelectOptions(provinceIndex, cityIndex, areaIndex)
            .setItemVisibleCount(10)
            .setLineSpacingMultiplier(2.2f)
            .setContentTextSize(16)
            .setTitleSize(16)
            .setSubCalSize(16)
            .setCancelColor(0xFF666666.toInt())
            .setSubmitColor(0xFFEC2D69.toInt())
            .build()
        pvOptions.setPicker(
            options1Items, options2Items as List<MutableList<Any>>?,
            options3Items as List<MutableList<MutableList<Any>>>?
        ) //三级选择器
        pvOptions.show()
    }
}